/**********************************
 * @Author: Your Name
 * @LastEditor: Your Name
 * @LastEditTime: 2025-11-07
 * Copyright © 2025 Your Name
 **********************************/

import { auditLogMockData } from './mock'

// 模拟API延迟
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

// 模拟分页处理
function handlePagination(data, params) {
  const page = params.page || 1
  const pageSize = params.pageSize || 10
  const start = (page - 1) * pageSize
  const end = start + pageSize
  return {
    list: data.slice(start, end),
    total: data.length,
    page,
    pageSize,
  }
}

// 模拟搜索过滤
function handleSearch(data, params) {
  let result = [...data]

  // 根据用户名过滤
  if (params.username) {
    result = result.filter(item => item.username.toLowerCase().includes(params.username.toLowerCase()))
  }

  // 根据操作类型过滤
  if (params.operation) {
    result = result.filter(item => item.operation.toLowerCase().includes(params.operation.toLowerCase()))
  }

  // 根据模块过滤
  if (params.module) {
    result = result.filter(item => item.module.toLowerCase().includes(params.module.toLowerCase()))
  }

  // 根据IP地址过滤
  if (params.ip) {
    result = result.filter(item => item.ip.includes(params.ip))
  }

  // 根据时间范围过滤
  if (params.startTime) {
    result = result.filter(item => new Date(item.operationTime) >= new Date(params.startTime))
  }

  if (params.endTime) {
    result = result.filter(item => new Date(item.operationTime) <= new Date(params.endTime))
  }

  return result
}

// 审计日志管理相关API (Mock版本)
export default {
  // 获取审计日志列表
  read: async (params = {}) => {
    await delay(500) // 模拟网络延迟

    // 获取所有日志数据
    let logs = [...auditLogMockData.logs]

    // 应用搜索过滤
    logs = handleSearch(logs, params)

    // 按操作时间倒序排列
    logs.sort((a, b) => new Date(b.operationTime) - new Date(a.operationTime))

    // 应用分页
    const pagination = handlePagination(logs, params)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: {
        list: pagination.list,
        total: pagination.total,
        page: pagination.page,
        pageSize: pagination.pageSize,
      },
    })
  },

  // 获取安全事件列表
  getSecurityEvents: async (params = {}) => {
    await delay(500) // 模拟网络延迟

    // 获取所有安全事件数据
    const events = [...auditLogMockData.securityEvents]

    // 应用分页
    const pagination = handlePagination(events, params)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: {
        list: pagination.list,
        total: pagination.total,
        page: pagination.page,
        pageSize: pagination.pageSize,
      },
    })
  },

  // 获取告警规则列表
  getAlertRules: async (params = {}) => {
    await delay(500) // 模拟网络延迟

    // 获取所有告警规则数据
    const rules = [...auditLogMockData.alertRules]

    // 应用分页
    const pagination = handlePagination(rules, params)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: {
        list: pagination.list,
        total: pagination.total,
        page: pagination.page,
        pageSize: pagination.pageSize,
      },
    })
  },

  // 创建告警规则
  createAlertRule: async (data) => {
    await delay(500) // 模拟网络延迟

    // 生成新的规则ID
    const newId = Math.max(...auditLogMockData.alertRules.map(r => r.id), 0) + 1

    // 创建新规则对象
    const newRule = {
      id: newId,
      name: data.name,
      description: data.description,
      condition: data.condition,
      severity: data.severity || 'MEDIUM',
      enabled: data.enabled !== undefined ? data.enabled : true,
      notifyChannels: data.notifyChannels || [],
      createdBy: data.createdBy || 1,
      updatedBy: data.updatedBy || 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }

    // 添加到规则列表
    auditLogMockData.alertRules.push(newRule)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: newRule,
    })
  },

  // 更新告警规则
  updateAlertRule: async (data) => {
    await delay(500) // 模拟网络延迟

    // 查找并更新规则
    const index = auditLogMockData.alertRules.findIndex(r => r.id === data.id)
    if (index === -1) {
      return Promise.reject({
        code: 404,
        message: '规则不存在',
      })
    }

    // 更新规则数据
    auditLogMockData.alertRules[index] = {
      ...auditLogMockData.alertRules[index],
      ...data,
      updatedAt: new Date().toISOString(),
    }

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: auditLogMockData.alertRules[index],
    })
  },

  // 删除告警规则
  deleteAlertRule: async (id) => {
    await delay(500) // 模拟网络延迟

    // 查找并删除规则
    const index = auditLogMockData.alertRules.findIndex(r => r.id === id)
    if (index === -1) {
      return Promise.reject({
        code: 404,
        message: '规则不存在',
      })
    }

    auditLogMockData.alertRules.splice(index, 1)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: null,
    })
  },

  // 获取操作类型选项
  getOperationOptions: async () => {
    await delay(300) // 模拟网络延迟

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: auditLogMockData.operationOptions,
    })
  },

  // 获取模块选项
  getModuleOptions: async () => {
    await delay(300) // 模拟网络延迟

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: auditLogMockData.moduleOptions,
    })
  },

  // 获取严重程度选项
  getSeverityOptions: async () => {
    await delay(300) // 模拟网络延迟

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: auditLogMockData.severityOptions,
    })
  },

  // 导出日志
  exportLogs: async (params = {}) => {
    await delay(1000) // 模拟导出延迟

    // 模拟导出结果
    const exportResult = {
      success: true,
      message: '日志导出成功',
      downloadUrl: '/mock-api/downloads/audit-logs-export.csv',
      fileName: `audit-logs-export-${new Date().toISOString().split('T')[0]}.csv`,
      fileSize: '2.4 MB',
    }

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: exportResult,
    })
  },
}
